<script setup lang="ts">
/**
 * @name ReportCenterEnergyConsumptionSummary
 * @description 能耗汇总统计
 */

import dayjs from 'dayjs'
import { Download, List } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'
import XLSX from 'xlsx-js-style'
import { useEnergyConsumptionSummary } from '@/mixins/ReportCenter/MixinEnergyConsumptionSummary'
import type { Point } from '@/components/ReadonlyPointTree/ReadonlyPointTree'
import { exportConsumptionSummaryStatistics } from '@/api/modules/consumption'
import { useSimpleExportLists } from '@/components/TableLists/useSimpleExportLists'
import IndicatorDataCurveModal from '@/components/IndicatorDataCurveModal/IndicatorDataCurveModal.vue'
import { STORAGE_MODES } from '@/enum/modules/indicator'

const dateRange = ref<[string, string]>([
  dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
  dayjs().format('YYYY-MM-DD'),
])
const indicatorDataCurveModalRef = ref<InstanceType<typeof IndicatorDataCurveModal>>()
const indicatorNumber = ref<string>()

const {
  loading,
  tableData,
  columns,
  getEnergyConsumptionSummaryData,
  loadEnergyConsumptionSummaryData,
} = useEnergyConsumptionSummary()
const [point, setPoint] = useState<Point | null>(null)
const doesDownloadAll = ref(true)
const tableRef = ref<TableInstance>()
const [downloading, setDownloading] = useState(false)
const route = useRoute()

async function loadMore(
  row: any,
  _treeNode: any,
  resolve: (data: any[]) => void,
) {
  const pointId = row.pointId
  if (pointId && row.hasLeaf) {
    loadEnergyConsumptionSummaryData(
      resolve,
      {
        pointId,
        startTime: unref(dateRange)[0],
        endTime: unref(dateRange)[1],
        all: false,
        isIncludeSelf: false,
      },
    )
  }
  else {
    resolve([])
  }
}

function handleClickNode(o: Point) {
  setPoint(o)
}
async function clickSearch() {
  const pointId = unref(point)?.id
  if (pointId) {
    await getEnergyConsumptionSummaryData({
      startTime: unref(dateRange)[0],
      endTime: unref(dateRange)[1],
      pointId,
      all: false,
      isIncludeSelf: true,
    })
    await nextTick()
    setTimeout(() => {
      const row = unref(tableData)[0]
      // console.log(unref(tableData));
      if (row) {
        // tableRef.value?.toggleRowExpansion(row, true);
      }
    }, 20)
  }
}

async function clickDownload() {
  const isAll = unref(doesDownloadAll)
  const cols = unref(columns)
  const pointId = unref(point)?.id

  try {
    if (isAll && pointId) {
      setDownloading(true)
      await exportConsumptionSummaryStatistics({
        pointId,
        all: true,
        isIncludeSelf: false,
        startTime: unref(dateRange)[0],
        endTime: unref(dateRange)[1],
      })
      return
    }

    const ws = XLSX.utils.table_to_sheet(unref(tableRef)?.$refs.tableBody)
    const data = XLSX.utils.sheet_to_json(ws, {
      header: cols.map(v => v.prop),
      skipHidden: true,
      raw: true,
    })

    const { exportXlsx } = useSimpleExportLists<any>({
      columns: unref(columns) as any,
      lists: data,
    })
    exportXlsx(route.meta.title || '能耗汇总统计')
  }
  catch (e) {
    console.warn(e)
  }
  finally {
    setDownloading(false)
  }
}

async function clickValue(code: string) {
  indicatorNumber.value = code
  await nextTick()
  indicatorDataCurveModalRef.value?.showModal()
}

watchEffect(() => {
  clickSearch()
})
</script>

<template>
  <div class="padding-sm flex container">
    <div class="points-container">
      <ReadonlyPointTree fire @click-node="handleClickNode" />
    </div>
    <div class="margin-left-sm flex-fillRemaining roll flex-direction flex">
      <div class="flex flex-shrink-0 items-center">
        <ElForm inline>
          <ElFormItem label="统计区间">
            <ElDatePicker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" :icon="List" @click="clickSearch">
              统计
            </ElButton>
          </ElFormItem>
        </ElForm>
        <ElCheckbox v-model="doesDownloadAll" class="ml-auto">
          导出全部
        </ElCheckbox>
        <ElButton :loading="downloading" class="ml-4" type="success" :icon="Download" @click="clickDownload">
          导出
        </ElButton>
      </div>
      <div class="roll flex-1">
        <ElTable
          ref="tableRef"
          v-loading="loading" :data="tableData"
          height="100%" row-key="uuid"
          lazy :load="loadMore"
          :tree-props="{ children: 'children', hasChildren: 'hasLeaf' }"
        >
          <template #empty>
            <TableEmpty />
          </template>
          <ElTableColumn
            v-for="(column, index) in columns" :key="index"
            :min-width="index === 0 ? 120 : undefined"
            :label="column.label" :prop="column.prop"
            :align="index === 0 ? 'left' : 'center'"
          >
            <template v-if="column.prop !== 'pointName'" #default="{ row }">
              <ElLink
                v-if="row[column.prop] !== '-' && row[`${column.prop}_indicatorNumber`]"
                type="primary"
                @click="clickValue(row[`${column.prop}_indicatorNumber`])"
              >
                <code>{{ row[column.prop] }}</code>
              </ElLink>
              <span v-else>{{ row[column.prop] }}</span>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </div>

    <!-- 指标数据折线图 -->
    <IndicatorDataCurveModal
      v-if="indicatorNumber"
      ref="indicatorDataCurveModalRef"
      title="指标数据折线图"
      :indicator-number="indicatorNumber"
      :initial-time-type="STORAGE_MODES.DAY"
      :initial-start-time="dateRange[0]"
      :initial-end-time="dateRange[1]"
    />
  </div>
</template>
